import json
import logging
from wxcloudrun import util
from django.http import JsonResponse
from django.shortcuts import render
from wxcloudrun.models import checkinfo
from wxcloudrun.models import tmpobj

logger = logging.getLogger('log')


def clear():  # 删除原有的数据
    data = checkinfo.objects.all()
    data.delete()


def clearone(date):  # 删除当天的数据
    # Counters.objects.get(id=1)
    d_date = util.getdatestr()
    if (date == None):
        pass
    else:
        d_date = date
    print(d_date)
    data = checkinfo.objects.filter(check_date=d_date)
    data.delete()


def savelog(str1):
    obj = tmpobj()
    obj.data = str(str1)
    obj.save()


def savedata(item):
    obj = checkinfo()
    obj._id = item.get('_id')
    obj._openid = item.get('_openid')
    obj.album = item.get('album')
    obj.area_id = item.get('area_id')
    obj.area_name = item.get('area_name')
    obj.check_date = item['check_date']
    obj.device = item.get('device')
    obj.fh_detail = item.get('fh_detail')
    obj.fh_value = item.get('fh_value')
    obj.insert_time = item.get('insert_time')
    obj.intnetip = item.get('intnetip')
    obj.ipaddress = item.get('ipaddress')
    obj.latitude = item.get('latitude')
    obj.localip = item.get('localip')
    obj.longitude = item.get('longitude')
    obj.user_id = item.get('user_id')
    obj.user_name = item.get('user_name')
    obj.fxs = item.get('fxs')
    obj.lous = item.get('lous')
    obj.xcs = item.get('xcs')
    obj.zhus = item.get('zhus')
    obj.save()


def adddata(request, _):
    '''
    增加小区数据
    '''
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    print(body)
    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    if request.method == 'POST' or request.method == 'post':
        # 增加数据
        if (body['action'] == 'save'):
            # 向数据表中保存数据
            dataobj = body['data']
            obj = checkinfo()
            obj.area_name = dataobj['area_name']
            obj.insert_time = dataobj['insert_time']
            obj.save()

        if (body['action'] == 'clear'):
            obj = checkinfo.objects.all()
            obj.delete()
            body = {'code': 0, 'errorMsg': ''}

        if (body['action'] == 'saveall'):
            clear()
            dataobj = body['data']
            for item in dataobj:
                savedata(item)
            body = {'code': 0, 'errorMsg': ''}

        if (body['action'] == 'oneday'):  # 更新当天的数据
            clearone(body.get('date'))
            dataobj = body['data']
            for item in dataobj:
                savedata(item)
            body = {'code': 0, 'errorMsg': '','result': str(body.get('date'))}

        rsp = JsonResponse(body, json_dumps_params={'ensure_ascii': False})
    else:
        rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                           json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))

    return rsp
